'''
E宝无忧少儿重疾险
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests

class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "E宝无忧少儿重疾险"

    # 生成产品数据
    def genProductInfo(self):

        # 年龄段
        years = []
        for i in range(8):

            if i<10:

                years.append('0'+str( i ))

            else:

                years.append( str(i) )

        # 性别 1男 2女
        gender = ["1","2"]

        # 保险金额
        amounts = ["10","15","20","25","30","40","50"]

        # 缴费方式 1 年缴  4 月缴
        payments = ["1","4"]

        # 缴费期限
        interval = ["05","10","15"]

        # 第一种情况
        for v in product( years,gender,amounts,payments,interval):

            # 写入数据库
            self.mysql.cursor.execute( domain['E宝无忧少儿重疾险']['insert_sql'].format( v[0],v[1],v[2],v[3],v[4]))

            self.mysql._conn.commit()


            print("第一种情况写入数据库成功")

        #第二种情况
        payments = ["5"]

        interval = ["0"]

        for v in product( years,gender,amounts,payments,interval ):

            # 写入数据库
            self.mysql.cursor.execute(domain['E宝无忧少儿重疾险']['insert_sql'].format(v[0], v[1], v[2], v[3], v[4]))

            self.mysql._conn.commit()

            print("第二种情况写入数据库成功")


        #第三种情况8岁为一个分界线
        for i in range(8,13):

            if i<10:

                years.append('0'+str( i ))

            else:

                years.append( str(i) )

        # 缴费方式 1 年缴  4 月缴
        payments = ["1", "4"]

        # 缴费期限
        interval = ["05", "10"]

        for v in product(years, gender, amounts, payments, interval):
            # 写入数据库
            self.mysql.cursor.execute(domain['E宝无忧少儿重疾险']['insert_sql'].format(v[0], v[1], v[2], v[3], v[4]))

            self.mysql._conn.commit()

            print("第三种情况写入数据库成功")

            # 第二种情况
            payments = ["5"]

            interval = ["0"]

        for v in product(years, gender, amounts, payments, interval):
            # 写入数据库
            self.mysql.cursor.execute(domain['E宝无忧少儿重疾险']['insert_sql'].format(v[0], v[1], v[2], v[3], v[4]))

            self.mysql._conn.commit()

            print("第四种情况写入数据库成功")

        # 第三种情况 13 岁为一个分界线
        for i in range(13, 15):

            if i < 10:

                years.append('0' + str(i))

            else:

                years.append(str(i))

        # 缴费方式 1 年缴  4 月缴
        payments = ["1", "4"]

        # 缴费期限
        interval = ["05"]

        for v in product(years, gender, amounts, payments, interval):
            # 写入数据库
            self.mysql.cursor.execute(domain['E宝无忧少儿重疾险']['insert_sql'].format(v[0], v[1], v[2], v[3], v[4]))

            self.mysql._conn.commit()

            print("第五种情况写入数据库成功")

            # 第二种情况
            payments = ["5"]

            interval = ["0"]

        for v in product(years, gender, amounts, payments, interval):
            # 写入数据库
            self.mysql.cursor.execute(domain['E宝无忧少儿重疾险']['insert_sql'].format(v[0], v[1], v[2], v[3], v[4]))

            self.mysql._conn.commit()

            print("第六种情况写入数据库成功")


    # 爬虫
    def requestJson(self,dt):

        code = self.filterCode( dt )

        data = {
            "pageName": "productAdd",
            "goods_id": "61865",
            "merchant_id": "B2C",
            "toubaoli_money":"",
            "productCode": "5000080" + code ,
            "productId": "512f037a-db34-4719-8b2b-11bb01ddee2f",
            "riskCode": "100000000" + code  ,
            "productName": "E宝无忧少儿重疾险",
            "insuredPrice": "",
            "insured.birthday":"",
            "templateType": "1",
            "employee_id":"",
            "channel": "GWSC - MENU - M31",
            "empNo":"",
            "newsCode":"",
            "twoMonthInsuredPrice":"",
            "loginUserId":"",
            "insured.age": "{0}".format( dt["year"]),
            "insured.sex": "{0}".format( dt["gender"]),
            "policy.amount": "{0}".format( dt["amount"]),
            "policy.chargeType":"{0}".format( dt["payment"]),
            "policy.chargeYear":"{0}".format( dt["interval"]),
            "policy.dateRemark": "25Y",
            "policy.showMessage": "true",
            "person.mobilenum": "承保短信将发送至您的手机"
        }

        r = requests.post( url = domain['E宝无忧少儿重疾险']['url'],headers=domain[self.name]["header"],data= data  )

        if r.status_code == 200:

            totalPrice = str(r.json()["totalPremium"])


            data = {
                "name":self.name,
                "id":dt["id"],
                "price":totalPrice,
            }

            #执行数据库更新操作
            self.mysql.updatePrice( data )

            print("产品价格更新成功:",data["price"])

        else:

            #任务执行失败
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("产品价格更新失败:",dt["id"])

    def filterCode(self,dt):

        riskCode = {

            "05": "0",
            "10": "1",
            "15": "2",
            "0": "3"

        }

        # 判断riskCode
        if dt["interval"] == "05":

            code = riskCode["05"]

            return code

        elif dt["interval"] == "10":

            code = riskCode["10"]

            return code

        elif dt["interval"] == "15":

            code = riskCode["15"]

            return code

        elif dt["interval"] == "0":

            code = riskCode["0"]

            return code

        else:

            return

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )


if __name__ == '__main__':

    s = Spider()

    # s.main()
    # s.genProductInfo()






